import React, { PureComponent, Fragment, Component } from 'react';
import { connect } from 'dva';
import {
  Row, Col, Card, Form, Input, Radio, Select, Icon, Button, Upload, List, Modal, message, Badge, TreeSelect, Tag, InputNumber, Spin,
} from 'antd';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './ParentRecomm.less';
import LayoutTypeModal from 'components/Content/ParentLayoutTypeModal';

import { routerRedux } from 'dva/router';
import ParentLayout from 'components/Content/ParentLayout';

import LayoutDetail1 from './ParentLayoutDetail1';
import LayoutDetail2 from './ParentLayoutDetail2';
import LayoutDetail3 from './ParentLayoutDetail3';
import Adv from './Adv';

const FormItem = Form.Item;

@connect(({ parentRecomm, loading }) => ({
  parentRecomm,
  channelTree: parentRecomm.channelTree,
  goodsList: parentRecomm.goodsList,
  loading: loading.models.parentRecomm,
}))
@Form.create()
export default class ParentRecommPage extends PureComponent {
  state = {
    modalVisible: false,
    record: null,
    layoutList: [],
    layoutList1: [],
    layoutList2: [],
    layoutList3: [],
    layoutList4: [],


    weight: null,
    current: null,  //当前正在添加的数组下标

    layoutType: null,
    layoutDetail: null,

    appType: null,

    advType: null,

    //广告相关
    adv: null,
    editType: null,
  };

  componentDidMount() {
    if (this.props.match.params.recommId != 'new') {
      this.props.dispatch({
        type: 'parentRecomm/fetchRecommPage',
        payload: { recommId: this.props.match.params.recommId },
        callback: (data) => this._setRecord(data)
      })
    }
    this.props.dispatch({
      type: 'parentRecomm/fetchChannelTree',
      payload: {},
    });



    // this._goodsSearch()
  }

  _advSearch() {
    this.props.dispatch({
      type: 'parentRecomm/fetchAdv',
      payload: { advType: this.state.advType },
      callback: (data) => this._setAdv(data)
    });
  }

  _setAdv(data) {
    this.setState({ adv: data })
  }

  _goodsSearch(filedValue) {
    this.props.dispatch({
      type: 'parentRecomm/fetchGoodsList',
      payload: filedValue,
    });
  }

  _search() {
    this.props.dispatch({
      type: 'parentRecomm/fetchRecommPage',
      payload: { recommId: this.props.match.params.recommId },
      callback: (data) => this._setRecord(data)
    })
  }



  _setRecord(data) {
    this.setState({advType: data.recommInfo.appType})
    this._advSearch(data.recommInfo.appType);
    console.log('设置-----------------', data)
    let layoutList1 = data.layoutList.filter(item => item.appType == 1)
    let layoutList2 = data.layoutList.filter(item => item.appType == 2)
    let layoutList3 = data.layoutList.filter(item => item.appType == 3)
    let layoutList4 = data.layoutList.filter(item => item.appType == 4)
    if (layoutList1 && (layoutList1.length > 0)) {
      let list = [];
      for (let i = 0; i < layoutList1.length; i++) {
        let one = layoutList1[i];
        one.weight = (i + 1) * 1000;
        list.push(one)
      }
      layoutList1 = list;
    }
    if (layoutList2 && (layoutList2.length > 0)) {
      let list = [];
      for (let i = 0; i < layoutList2.length; i++) {
        let one = layoutList2[i];
        one.weight = (i + 1) * 1000;
        list.push(one)
      }
      layoutList2 = list;
    }
    if (layoutList3 && (layoutList3.length > 0)) {
      let list = [];
      for (let i = 0; i < layoutList3.length; i++) {
        let one = layoutList3[i];
        one.weight = (i + 1) * 1000;
        list.push(one)
      }
      layoutList3 = list;
    }
    if (layoutList4 && (layoutList4.length > 0)) {
      let list = [];
      for (let i = 0; i < layoutList4.length; i++) {
        let one = layoutList4[i];
        one.weight = (i + 1) * 1000;
        list.push(one)
      }
      layoutList4 = list;
    }
    this.setState({
      record: data,
      layoutList: data.layoutList,
      layoutList1,
      layoutList2,
      layoutList3,
      layoutList4,
      layoutDetail: null
    })
  }

  _addFristLayout(appType) {
    this.setState({ weight: 1000, current: 0, appType: appType })
    this._setModalVisible(true)
  }

  _addLayout(item, i, type) {
    console.log(i)
    let { record, layoutList1, layoutList2, layoutList3, layoutList4 } = this.state;
    let weight = null;
    if (type == 1) {
      if ((i + 1) == layoutList1.length) {  //点击最后一项的添加布局
        weight = item.weight + 1000;
      } else if ((i + 1) < (layoutList1.length)) {  //点击中间的
        weight = parseInt((item.weight + layoutList1[i + 1].weight) / 2)
      }
    }

    if (type == 2) {
      if ((i + 1) == layoutList2.length) {  //点击最后一项的添加布局
        weight = item.weight + 1000;
      } else if ((i + 1) < (layoutList2.length)) {  //点击中间的
        weight = parseInt((item.weight + layoutList2[i + 1].weight) / 2)
      }
    }

    if (type == 3) {
      if ((i + 1) == layoutList3.length) {  //点击最后一项的添加布局
        weight = item.weight + 1000;
      } else if ((i + 1) < (layoutList3.length)) {  //点击中间的
        weight = parseInt((item.weight + layoutList3[i + 1].weight) / 2)
      }
    }

    if (type == 4) {
      if ((i + 1) == layoutList4.length) {  //点击最后一项的添加布局
        weight = item.weight + 1000;
      } else if ((i + 1) < (layoutList4.length)) {  //点击中间的
        weight = parseInt((item.weight + layoutList4[i + 1].weight) / 2)
      }
    }


    console.log('要添加的权重', weight)

    this.setState({ weight: weight, current: i + 1, appType: item.appType })

    this._setModalVisible(true)
  }

  _setModalVisible(flag) {
    this.setState({ modalVisible: flag })
  }

  _chooseType(type) {
    this.props.dispatch({
      type: 'parentRecomm/addRecommPageLayout',
      payload: { recommId: this.props.match.params.recommId, layoutStyle: type, weight: this.state.weight, appType: this.state.appType },
      callback: () => this._addLayoutBack()
    })
  }

  _addLayoutBack() {
    this.setState({
      modalVisible: false,
      weight: null,
      current: null,
      appType: null,
    })
    this._search()
  }

  _deleteLayout(item, i) {
    this.props.dispatch({
      type: 'parentRecomm/deletePageLayout',
      payload: { layoutId: item.layoutId },
      callback: () => this._search()
    })
  }

  _editLayout(item, i) {
    console.log('布局详情', item)
    let newOne = {...item}
    this.setState({ layoutDetail: newOne, editType: 'detail' })
  }

  swapArray(arr, index1, index2) {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
  }

  _forwardLayout(oldList, item, i, type) {
    console.log('iiiiiiiiiiiiiii', i)
    if (i == 0) return;
    let record = this.state.record;
    // let oldList = this.state.layoutList;
    console.log('老的数组》》》》》》》》》', oldList)

    let before = oldList[(i - 1)];
    let click = oldList[i];

    console.log('before》》》》》》》》》', before)
    console.log('click》》》》》》》》》', click)

    let newList = [];
    for (let j = 0; j < oldList.length; j++) {
      if (j == (i - 1)) {
        newList.push(click)
      } else if (j == i) {

        newList.push(before)
      } else {
        newList.push(oldList[j])
      }
    }

    if (newList && (newList.length > 0)) {
      let list = [];
      for (let k = 0; k < newList.length; k++) {
        let one = newList[k];
        one.weight = (k + 1) * 1000;
        list.push(one)
      }
      newList = list;
    }

    console.log('新的数组》》》》》》》》》', newList)

    switch (type) {
      case 1: this.setState({ layoutList1: newList }); break;
      case 2: this.setState({ layoutList2: newList }); break;
      case 3: this.setState({ layoutList3: newList }); break;
      case 4: this.setState({ layoutList4: newList }); break;
    }
  }

  _backLayout(oldList, item, i, type) {
    console.log('iiiiiiiiiiiiiii', i)
    if (i == oldList.length) return;
    let record = this.state.record;
    // let oldList = this.state.layoutList;
    console.log('老的数组》》》》》》》》》', oldList)

    let after = oldList[(i + 1)];
    let click = oldList[i];

    let newList = [];
    for (let j = 0; j < oldList.length; j++) {
      if (j == (i)) {
        newList.push(after)
      } else if (j == (i + 1)) {
        newList.push(click)
      } else {
        newList.push(oldList[j])
      }
    }
    if (newList && (newList.length > 0)) {
      let list = [];
      for (let k = 0; k < newList.length; k++) {
        let one = newList[k];
        one.weight = (k + 1) * 1000;
        list.push(one)
      }
      newList = list;
    }

    switch (type) {
      case 1: this.setState({ layoutList1: newList }); break;
      case 2: this.setState({ layoutList2: newList }); break;
      case 3: this.setState({ layoutList3: newList }); break;
      case 4: this.setState({ layoutList4: newList }); break;
    }
  }

  _savePage() {
    console.log('最终保存数据', this.state.record)
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) return;
      let values = {};
      values['recommId'] = this.state.record.recommInfo.recommId;
      // values['appType'] = this.state.record.recommInfo.appType;
      values['recommName'] = fieldsValue.recommName;

      let list = []
      if (this.state.layoutList1 && (this.state.layoutList1.length > 0)) {
        for (let i = 0; i < this.state.layoutList1.length; i++) {
          let one = this.state.layoutList1[i];
          let newOne = {};
          newOne['layoutStyle'] = one.layoutStyle;
          newOne['appType'] = one.appType;
          newOne['layoutId'] = one.layoutId;
          newOne['weight'] = one.weight;
          list.push(newOne)
        }
      }
      if (this.state.layoutList2 && (this.state.layoutList2.length > 0)) {
        for (let i = 0; i < this.state.layoutList2.length; i++) {
          let one = this.state.layoutList2[i];
          let newOne = {};
          newOne['layoutStyle'] = one.layoutStyle;
          newOne['appType'] = one.appType;
          newOne['layoutId'] = one.layoutId;
          newOne['weight'] = one.weight;
          list.push(newOne)
        }
      }
      if (this.state.layoutList3 && (this.state.layoutList3.length > 0)) {
        for (let i = 0; i < this.state.layoutList3.length; i++) {
          let one = this.state.layoutList3[i];
          let newOne = {};
          newOne['layoutStyle'] = one.layoutStyle;
          newOne['appType'] = one.appType;
          newOne['layoutId'] = one.layoutId;
          newOne['weight'] = one.weight;
          list.push(newOne)
        }
      }
      if (this.state.layoutList4 && (this.state.layoutList4.length > 0)) {
        for (let i = 0; i < this.state.layoutList4.length; i++) {
          let one = this.state.layoutList4[i];
          let newOne = {};
          newOne['layoutStyle'] = one.layoutStyle;
          newOne['appType'] = one.appType;
          newOne['layoutId'] = one.layoutId;
          newOne['weight'] = one.weight;
          list.push(newOne)
        }
      }

      values['layoutList'] = list;

      console.log('listlistlistlistlistlistlist', list)

      this.props.dispatch({
        type: 'parentRecomm/editPageLayout',
        payload: values,
        callback: () => this._search()
      })
    })
  }


  render() {
    const { record, layoutList, layoutList1, layoutList2, layoutList3, layoutList4, layoutDetail } = this.state;
    const { form } = this.props;
    return (
      <PageHeaderLayout>
        <div className={styles.container}>
          <div className={styles.leftContainer}>
            <div className={styles.header}>
              精选
            </div>

            <div className={styles.phoneContainer}>
              <div className={styles.advContainer}>
                运营位推荐
              <Button style={{ marginTop: '20px' }} type="primary" onClick={() => { this.setState({ editType: 'adv' }) }} >编辑</Button>
              </div>

              <div>
                <div className={styles.channelText}>小萌早教</div>
                <div className={styles.layoutContainer}>
                  {layoutList1 && (layoutList1.length > 0) ?
                    layoutList1.map((item, i) =>
                      <ParentLayout item={item} key={item.layoutId} first={layoutList1[0].weight} last={layoutList1[layoutList1.length - 1].weight}
                        editLayout={() => this._editLayout(item, i)}
                        forwardLayout={() => this._forwardLayout(layoutList1, item, i, 1)}
                        backLayout={() => this._backLayout(layoutList1, item, i, 1)}
                        addLayout={() => this._addLayout(item, i, 1)}
                        deleteLayout={() => this._deleteLayout(item, i)}
                      />)
                    :
                    <div style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                      <Button type="primary" onClick={() => this._addFristLayout(1)} >添加布局</Button>
                    </div>
                  }
                </div>
                <div className={styles.channelText}>小萌绘本</div>
                <div className={styles.layoutContainer}>
                  {layoutList2 && (layoutList2.length > 0) ?
                    layoutList2.map((item, i) =>
                      <ParentLayout item={item} key={item.layoutId} first={layoutList2[0].weight} last={layoutList2[layoutList2.length - 1].weight}
                        editLayout={() => this._editLayout(item, i)}
                        forwardLayout={() => this._forwardLayout(layoutList2, item, i, 2)}
                        backLayout={() => this._backLayout(layoutList2, item, i, 2)}
                        addLayout={() => this._addLayout(item, i, 2)}
                        deleteLayout={() => this._deleteLayout(item, i)}
                      />)
                    :
                    <div style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                      <Button type="primary" onClick={() => this._addFristLayout(2)} >添加布局</Button>
                    </div>
                  }
                </div>

                <div className={styles.channelText}>萌萌乐视频</div>
                <div className={styles.layoutContainer}>
                  {layoutList3 && (layoutList3.length > 0) ?
                    layoutList3.map((item, i) =>
                      <ParentLayout item={item} key={item.layoutId} first={layoutList3[0].weight} last={layoutList3[layoutList3.length - 1].weight}
                        editLayout={() => this._editLayout(item, i)}
                        forwardLayout={() => this._forwardLayout(layoutList3, item, i, 3)}
                        backLayout={() => this._backLayout(layoutList3, item, i, 3)}
                        addLayout={() => this._addLayout(item, i, 3)}
                        deleteLayout={() => this._deleteLayout(item, i)}
                      />)
                    :
                    <div style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                      <Button type="primary" onClick={() => this._addFristLayout(3)} >添加布局</Button>
                    </div>
                  }
                </div>

                <div className={styles.channelText}>萌萌乐儿歌</div>
                <div className={styles.layoutContainer}>
                  {layoutList4 && (layoutList4.length > 0) ?
                    layoutList4.map((item, i) =>
                      <ParentLayout item={item} key={item.layoutId} first={layoutList4[0].weight} last={layoutList4[layoutList4.length - 1].weight}
                        editLayout={() => this._editLayout(item, i)}
                        forwardLayout={() => this._forwardLayout(layoutList4, item, i, 4)}
                        backLayout={() => this._backLayout(layoutList4, item, i, 4)}
                        addLayout={() => this._addLayout(item, i, 4)}
                        deleteLayout={() => this._deleteLayout(item, i)}
                      />)
                    :
                    <div style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                      <Button type="primary" onClick={() => this._addFristLayout(4)} >添加布局</Button>
                    </div>
                  }
                </div>

                <div style={{ marginTop: '15px' }}>
                  <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} label="页面名称" >
                    {form.getFieldDecorator('recommName', {
                      initialValue: (record && record.recommInfo && record.recommInfo.recommName) ? record.recommInfo.recommName : null,
                      rules: [{ required: true, message: '请输入页面名称' }],
                    })(<Input placeholder="请输入页面名称" maxLength="10" />)}
                  </FormItem>
                  <FormItem>
                    <Button type="primary" onClick={() => this._savePage()}>保存</Button>
                    <Button type="primary" style={{ marginLeft: '30px' }} onClick={() => { this.props.dispatch(routerRedux.goBack()) }}>返回列表</Button>
                  </FormItem>
                </div>

              </div>

            </div>


          </div>

          <div className={styles.rightContainer}>
            {this.state.editType == 'adv' ?
              <Adv advDetailList={this.state.adv.advDetailList} advId={this.state.adv.advInfo.advId}
                advOk={() => this._okAdv()} advCancel={() => this._advCancel()}
                advSearch={() => this._advSearch()} loading={this.props.loading}
              />
              :
              this.state.editType == 'detail' ?

                <div style={{ display: 'flex', flexDirection: 'column', justifyContent: "center", alignItems: 'center' }}>
                  {layoutDetail ?
                    ((layoutDetail.layoutStyle == '0')) ?
                      <div className={styles.editItem}>
                        <LayoutDetail1 layoutDetail={layoutDetail}
                          channelTree={this.props.channelTree} goodsList={this.props.goodsList}
                          goodsSearch={(filedValue) => this._goodsSearch(filedValue)}
                          recommPageSearch={() => this._search()}
                        />
                      </div>
                      :
                      ((layoutDetail.layoutStyle == '1')) ?
                        <div className={styles.editItem2}>
                          <LayoutDetail2 layoutDetail={layoutDetail}
                            channelTree={this.props.channelTree} goodsList={this.props.goodsList}
                            goodsSearch={(filedValue) => this._goodsSearch(filedValue)}
                            recommPageSearch={() => this._search()}
                          />
                        </div>
                        :
                        ((layoutDetail.layoutStyle == '2')) ?
                          <div className={styles.editItem3}>
                            <LayoutDetail3 layoutDetail={layoutDetail}
                              channelTree={this.props.channelTree} goodsList={this.props.goodsList}
                              goodsSearch={(filedValue) => this._goodsSearch(filedValue)}
                              recommPageSearch={() => this._search()}
                            />
                          </div>
                          :
                          null
                    :
                    null
                  }
                  <div style={{ height: '100px' }}></div>
                </div>
                :

                null
            }

          </div>



          <LayoutTypeModal visible={this.state.modalVisible} chooseType={(type) => this._chooseType(type)}
            cancel={() => this._setModalVisible(false)}
          />


        </div>
      </PageHeaderLayout>
    )
  }
}